import './app.scss'
import {useState,useRef} from 'react';

export default () => {
    
    const [pos,setPos] = useState({left:0,top:0});

    const moveDraggier = (()=>{

        const dragData = useRef({
            startTop: 0, //拖拽开始的时候,block的top值
            startLeft: 0,   //拖拽开始的时候,block的left值
            startX: 0,  //拖拽开始的时候，鼠标的left值
            startY: 0   //拖拽开始的时候，鼠标的top值
        })

        const mousedown = (e: React.MouseEvent<HTMLDivElement>) => {
            document.addEventListener('mousemove',mousemove);
            document.addEventListener('mouseup',mouseup);
            dragData.current = {
                startTop: pos.top,
                startLeft: pos.left,
                startX: e.clientX,
                startY: e.clientY
            }
        }

        const mousemove = (e: MouseEvent) => {
            //move的过程中,需要获取hook变量
            console.log(JSON.stringify(pos));

            const {startX,startY,startTop,startLeft} = dragData.current
            const durX = e.clientX - startX;
            const durY = e.clientY - startY;
            setPos({
                top: startTop + durY,
                left: startLeft + durX
            })
        }

        const mouseup = (e: MouseEvent) => {
            document.removeEventListener('mousemove',mousemove)
            document.removeEventListener('mouseup',mouseup)
        }
        return {
            mousedown
        }
    })();

    return (
        <div className="app-home">
            <h1>hello world</h1>

            <div style={{
                height: '50px',
                width: '50px',
                backgroundColor: 'black',
                position: 'relative',
                top: `${pos.top}px`,
                left: `${pos.left}px`,
                display: 'inline-block'
            }}
            onMouseDown={moveDraggier.mousedown}
            />
        </div>
    )
}